package com.myutils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.reader.base.CMD;
import com.reader.base.ReaderBase;
import com.reader.helper.ISO180006BOperateTagBuffer;
import com.reader.helper.InventoryBuffer;
import com.reader.helper.OperateTagBuffer;
import com.reader.helper.ReaderHelper;
import com.reader.helper.ReaderSetting;
import com.sinopec.basemodule.common.Logger;

import org.jetbrains.annotations.NotNull;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 类描述：UHF 扫码帮助类 <br/>
 * 创建人：lwj<br/>
 * 创建时间：2019/8/13 15:09 <br/>
 */
public class UHFUtils {
    private ReaderBase mReader;
    private ReaderHelper mReaderHelper;

    private static ReaderSetting m_curReaderSetting;
    private static InventoryBuffer m_curInventoryBuffer;
    private static OperateTagBuffer m_curOperateTagBuffer;
    private static ISO180006BOperateTagBuffer m_curOperateTagISO18000Buffer;

    boolean mKeyPressing = false;
    private Disposable mDisposable;

    @SuppressWarnings("UnstableApiUsage")
    private static final Scheduler FROM_SCHEDULER = Schedulers.from(Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(@NotNull Runnable r) {
            return new Thread(r, "uhf-thread");
        }
    }), true);

    public interface ScanCallback {
        /**
         * 检查当前是否被销毁，再刷新
         */
        void refreshText();

        /**
         * 检查当前是否被销毁，再刷新
         */
        void refreshList();

        /**
         * 检查当前是否被销毁，再刷新
         */
        void refreshStartStop(boolean start);
    }

    private ScanCallback mScanCallback;

    void setScanCallback(ScanCallback scanCallback) {
        mScanCallback = scanCallback;
    }

    public interface SetCallback {
        void refreshPower();

        void refreshTemperature();
    }

    private SetCallback mSetCallback;

    void setSetCallback(SetCallback setCallback) {
        mSetCallback = setCallback;
    }

    private UHFUtils() {
    }

    ReaderBase getReader() {
        return mReader;
    }

    ReaderHelper getReaderHelper() {
        return mReaderHelper;
    }

    static ReaderSetting getM_curReaderSetting() {
        return m_curReaderSetting;
    }

    static InventoryBuffer getM_curInventoryBuffer() {
        return m_curInventoryBuffer;
    }

    static OperateTagBuffer getM_curOperateTagBuffer() {
        return m_curOperateTagBuffer;
    }

    static ISO180006BOperateTagBuffer getM_curOperateTagISO18000Buffer() {
        return m_curOperateTagISO18000Buffer;
    }

    static UHFUtils newInstance() {
        return new UHFUtils();
    }

    /**
     * 初始化
     */
    void init() {
        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            e.printStackTrace();
        }

        m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();
        m_curOperateTagBuffer = mReaderHelper.getCurOperateTagBuffer();
        m_curOperateTagISO18000Buffer = mReaderHelper.getCurOperateTagISO18000Buffer();
    }

    void onDestroy() {
        setScanCallback(null);
        unregisterScanReceiver();
        unregisterSetReceiver();
        clearList();
    }

    // add by lei.li 2016/11/14
    private BroadcastReceiver mScanCodeReceiver = null;

    private LocalBroadcastManager mLbm;

    void addScanCodeReceiver(Context context) {
        if (mLbm == null) {
            mLbm = LocalBroadcastManager.getInstance(context);
        }
        if (mScanCodeReceiver == null) {
            mScanCodeReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action == null) {
                        return;
                    }
                    if (action.equals(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG)) {
                        byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);
                        Logger.e("123===", "6c 接受广播== btCmd=" + btCmd);
                        switch (btCmd) {
                            case CMD.GET_ACCESS_EPC_MATCH:
                                //m_curOperateTagBuffer.strAccessEpcMatch
                                break;
                            case CMD.READ_TAG:
                            case CMD.WRITE_TAG:
                            case CMD.LOCK_TAG:
                            case CMD.KILL_TAG:
                                if (mScanCallback != null) {
                                    mScanCallback.refreshList();
                                    mScanCallback.refreshText();
                                }
                                break;
                        }
                    } else if (action.equals(ReaderHelper.BROADCAST_WRITE_LOG)) {
                       /* mLogList.writeLog((String) intent.getStringExtra("log"),
                                intent.getIntExtra("type", ERROR.SUCCESS));*/
                    }
                    /*else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_READER_SETTING)) {
                        String[] strs = mLogList.getTitleInfo().toString().split("  ");
                        Logger.d(TAG, "onReceive: " + strs[0]);
                        if (m_curReaderSetting.btReaderStatus == 0x13) {
                            mLogList.setTitleInfo(strs[0] + "  ");
                        } else if (m_curReaderSetting.btReaderStatus == -1) {
                        } else {
                            if (!strs[strs.length - 1].equals("<" +
                                    context.getResources().getString(R.string.auto_read_model) + ">")) {
                                SpannableString tSS = new SpannableString(strs[0] + "  " + "  <" +
                                        context.getResources().getString(R.string.auto_read_model) + ">");
                                tSS.setSpan(new ForegroundColorSpan(Color.RED), 0, tSS.length(),
                                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                mLogList.setTitleInfo(tSS);
                            }
                        }
                    }*/
                }
            };
        }
        IntentFilter intent = new IntentFilter();
        intent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        intent.addAction(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG);
        mLbm.registerReceiver(mScanCodeReceiver, intent);
    }

    private void unregisterScanReceiver() {
        if (mLbm != null && mScanCodeReceiver != null) {
            mLbm.unregisterReceiver(mScanCodeReceiver);
        }
    }

    private BroadcastReceiver mSetReceiver = null;

    void addUhfSetReceiver(Context context) {
        if (mLbm == null) {
            mLbm = LocalBroadcastManager.getInstance(context);
        }
        if (mSetReceiver == null) {
            mSetReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_READER_SETTING)) {
                        byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);

                        if (btCmd == CMD.GET_OUTPUT_POWER
                                || btCmd == CMD.SET_OUTPUT_POWER) {
                            if (mSetCallback != null) {
                                mSetCallback.refreshPower();
                            }
                        } else if (btCmd == CMD.GET_READER_TEMPERATURE) {
                            if (mSetCallback != null) {
                                //刷新温度
                                mSetCallback.refreshTemperature();
                            }
                        }
                    } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {
                        //mLogList.writeLog((String)intent.getStringExtra("log"), intent.getIntExtra("type", ERROR.SUCCESS));
                    }
                }
            };
        }
        IntentFilter itent = new IntentFilter();
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_READER_SETTING);
        mLbm.registerReceiver(mSetReceiver, itent);
    }

    @SuppressWarnings("WeakerAccess")
    void unregisterSetReceiver() {
        if (mLbm != null && mSetReceiver != null) {
            mLbm.unregisterReceiver(mSetReceiver);
        }
    }

    void clearList() {
        //清空数据
        m_curOperateTagBuffer.clearBuffer();
        //m_curInventoryBuffer.clearInventoryRealResult();
        if (mScanCallback != null) {
            mScanCallback.refreshList();
            mScanCallback.refreshText();
        }
    }

    void startStopBt(boolean isStart) {
        if (mKeyPressing == isStart) {
            return;
        }
        mKeyPressing = isStart;
        if (mScanCallback != null) {
            mScanCallback.refreshStartStop(mKeyPressing);
        }
        m_curOperateTagBuffer.dtStartTag = new Date();
        if (isStart) {
            mDisposable = Observable.
                    interval(0, 300, TimeUnit.MILLISECONDS)
                    .observeOn(FROM_SCHEDULER)
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            Logger.e("123===", Thread.currentThread().getName() + "======================================================" + aLong);
                            //读标签
                            readTag();
                        }
                    });
        } else {
            if (mDisposable != null) {
                if (!mDisposable.isDisposed()) {
                    mDisposable.dispose();
                }
            }
        }
    }

    /**
     * 读标签
     */
    private void readTag() {
        Logger.e("123===", "6c 读标签");
        byte btMemBank = 0x00;
        byte btWordAdd = 0x00;
        byte btWordCnt = 0x00;
        byte[] btAryPassWord = null;
        //密码区
        //btMemBank = 0x00;
        //epc区
        //btMemBank = 0x01;
        //tid区
        //btMemBank = 0x02;
        //user区
        btMemBank = 0x03;

        /*try {
            //获取其实地址
            btWordAdd = (byte) Integer.parseInt(mStartAddrEditText.getText().toString());
        } catch (Exception e) {
            //起始地址格式错误
            return;
        }

        try {
            //获取密码
            String[] reslut = StringTool.stringToStringArray(mPasswordEditText.getText().toString().toUpperCase(), 2);
            btAryPassWord = StringTool.stringArrayToByteArray(reslut, 4);
        } catch (Exception e) {
            //密码格式错误
            return;
        }*/

        //读标签
        try {
            //获取数据长度
            //(byte) (Integer.parseInt(mDataLenEditText.getText().toString()));
            btWordCnt = (byte) 3;
        } catch (Exception e) {
            //数据长度格式错误
            return;
        }

        /*if ((btWordCnt & 0xFF) <= 0) {
            //数据长度格式错误
            return;
        }*/

        //清空数据
        //m_curOperateTagBuffer.clearBuffer();
        mReader.readTag(m_curReaderSetting.btReadId, btMemBank, btWordAdd, btWordCnt, btAryPassWord);
    }
}
